package com.jinghua.treatment.websocket;


import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.entity.SysImMessages;
import com.jinghua.treatment.entity.SysPatient;
import com.jinghua.treatment.mapper.SysImMessagesMapper;
import com.jinghua.treatment.service.IMMessageService;
import com.jinghua.treatment.service.SysDoctorService;
import com.jinghua.treatment.service.SysPatientService;
import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.wechat.util.HttpUtil;
import com.jinghua.treatment.wechat.util.ThreadPoolManager;
import com.jinghua.treatment.wechat.util.WechatUtil;
import org.apache.log4j.Logger;
import org.quartz.spi.ThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Properties;

@Controller
public class WebSocketController {
    Logger log   = Logger.getLogger(WebSocketController.class);

    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private SysDoctorService sysDoctorService;

    @Autowired
    private SysPatientService sysPatientService;

    @Autowired
    private IMMessageService imMessageService;


    /**
     * 点对点聊天
     * @param msg
     * @return
     */
    @MessageMapping("/p2pchat")
    public void p2pchat(WSMsg  msg,SimpMessageHeaderAccessor accessor) {
        String sessionId  =   sessionId=getSessionIdFromMap(msg.getToId());
        if(sessionId!=null) {
            simpMessagingTemplate.convertAndSendToUser(sessionId, "/chat/backMsg", msg, createHeaders(sessionId));
            storeToDB(msg);
        }else{//对方不在线，发送微信消息
            //sessionId=getSessionIdFromMap(msg.getFromId());
            //simpMessagingTemplate.convertAndSendToUser(sessionId,"/chat/warn","对方暂不在线",createHeaders(sessionId));
            if("doctor".equals(msg.getClientType())){//发送者为医生，找患者
                SysPatient  sysPatient = sysPatientService.selectById(Integer.valueOf(msg.getToId()));
                SysDoctor sysDoctor = sysDoctorService.findById(Integer.valueOf(msg.getFromId()));
                sendWCMSG(sysPatient.getWechat(),sysDoctor.getDoctorname() +"医生给您发来了消息 \n\r\n\r<a href='"+ PropertyUtil.getConfig("app.server")+"/mod-page/patient/my_doctor_detail.html?patientId="+sysPatient.getPatientId()+"&doctorId="+sysDoctor.getDoctorId()+"'>> 立即回复TA <<</a>");
            }else if("patient".equals(msg.getClientType())){//发送者为患者，找医生
                SysPatient  sysPatient = sysPatientService.selectById(Integer.valueOf(msg.getFromId()));
                SysDoctor sysDoctor = sysDoctorService.findById(Integer.valueOf(msg.getToId()));
                sendWCMSG(sysDoctor.getWechat(),sysPatient.getPatientname() +"患者给您发来了消息 \n\r\n\r<a href='"+ PropertyUtil.getConfig("app.server")+"/mod-page/im/user_chat.html?pid="+sysPatient.getPatientId()+"&did="+sysDoctor.getDoctorId()+"&tag=consult'> >> 立即回复TA << </a>");
            }
            storeToDB(msg);
        }
    }

    public void storeToDB(final WSMsg  msg){
        //异步数据保存
        ThreadPoolManager.newInstance().addExecuteTask(new Runnable() {
            public void run() {
                SysImMessages sysImMessages  = new SysImMessages();
                Integer  fromId= Integer.valueOf(msg.getFromId());
                Integer toId = Integer.valueOf(msg.getToId());
                sysImMessages.setFromId(fromId);
                sysImMessages.setMsgType(msg.getMsgType());
                sysImMessages.setToId(toId);
                if("doctor".equals(msg.getClientType())){
                    SysDoctor sysDoctor = sysDoctorService.findById(fromId);
                    SysPatient sysPatient = sysPatientService.selectById(toId);
                    sysImMessages.setFromWechat(sysDoctor.getWechat());
                    sysImMessages.setToWechat(sysPatient.getWechat());
                    sysImMessages.setWhos("doctor");
                }else if("patient".equals(msg.getClientType())){
                    SysDoctor sysDoctor = sysDoctorService.findById(toId);
                    SysPatient sysPatient = sysPatientService.selectById(fromId);
                    sysImMessages.setFromWechat(sysPatient.getWechat());
                    sysImMessages.setToWechat(sysDoctor.getWechat());
                    sysImMessages.setWhos("patient");
                }
                sysImMessages.setMsgContent(msg.getMsg());
                sysImMessages.setMsgStatus("0");
                sysImMessages.setSendTime(new Date());
                sysImMessages.setUuid(IDGenerator.uuid());
                imMessageService.save(sysImMessages);
            }
        });
    }

    public String getSessionIdFromMap(String key){
        try{
            return  webAgentSessionRegistry.getSessionIds(key).stream().findFirst().get();
        }catch (NoSuchElementException e){
            log.error(e.getMessage());
            log.warn("user may not online");
        }
        return null;
    }

    private MessageHeaders createHeaders(String sessionId) {
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        return headerAccessor.getMessageHeaders();
    }

    private void sendWCMSG(String toOpenId,String msg){
        String token   = WechatUtil.getAccessToken();
        log.debug("token:"+token);
        log.debug("toOpenId:"+toOpenId);
        String url  = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
        String json = "{\"touser\":\""+toOpenId+"\",\"msgtype\":\"text\",\"text\":{\"content\":\""+msg+"\"}}";
        String response  =   HttpUtil.sendPostRequest(url,json,"json");
        log.debug("wcresponse:"+response);
    }
}
